package org.example.booklist.Controller;
import ch.qos.logback.core.util.StringUtil;
import jakarta.servlet.http.HttpSession;
import org.example.booklist.constant.Constants;
import org.example.booklist.model.UserInfo;
import org.example.booklist.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")

public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(@RequestParam String userName, @RequestParam String password , HttpSession session){
        //1。校验参数
        //2. 验证密码是否正确
        //3.返回响应结果：
        System.out.println("收到登录请求，用户名: " + userName + "，密码: " + password);
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return "用户名或者密码为空";
        }

        if(!"admin".equals(userName) || !"admin".equals(password)){
            return "密码错误";
        }

        //根据用户名称，去数据库中查询用户信息，如果没有查询到，说明用户不存在
        //如果查询到了用户信息，那么就开始校对密码是否正确：

        UserInfo userInfo = userService.getUserInfoByName(userName);
        if(userInfo == null){
            return "用户不存在";
        }

        //如果用户存在，那么就开始校验密码是否正确:
        if(!password.equals(userInfo.getPassword())){
            return "密码错误";
        }
        //如果密码正确，就直接注入：
        session.setAttribute(Constants.USER_SESSION_KEY,userInfo);
        return "";
    }

}